/*
 Copyright (c) 2002-2011 ymnk, JCraft,Inc. All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
 this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright 
 notice, this list of conditions and the following disclaimer in 
 the documentation and/or other materials provided with the distribution.

 3. The names of the authors may not be used to endorse or promote products
 derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
 INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.yisin.ssh2.jsch;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Queue;
import java.util.Vector;
import java.util.concurrent.LinkedTransferQueue;

import com.yisin.ssh2.EventDelegate;
import com.yisin.ssh2.EventHandler;

/**
 * The abstract base class for the different types of channel which may be
 * associated with a {@link Session}.
 *
 * <p>
 * It should be considered an implementation detail that Channel implements
 * {@link Runnable} &ndash; external code never has to invoke the {@link #run}
 * method.
 * </p>
 *
 * @see Session#openChannel
 */
public abstract class Channel implements Runnable {

	static final int SSH_MSG_CHANNEL_OPEN_CONFIRMATION = 91;
	static final int SSH_MSG_CHANNEL_OPEN_FAILURE = 92;
	static final int SSH_MSG_CHANNEL_WINDOW_ADJUST = 93;

	static final int SSH_OPEN_ADMINISTRATIVELY_PROHIBITED = 1;
	static final int SSH_OPEN_CONNECT_FAILED = 2;
	static final int SSH_OPEN_UNKNOWN_CHANNEL_TYPE = 3;
	static final int SSH_OPEN_RESOURCE_SHORTAGE = 4;

	static int index = 0;
	private static Vector<Channel> pool = new Vector<Channel>();
	private Queue<String> msgQueue = new LinkedTransferQueue<String>();
	private EventDelegate eventDelegate = new EventDelegate();

	public void regEvent(EventHandler handler) {
		eventDelegate.add(handler);
	}

	/**
	 * Creates a new Channel of specified type. This factory method is used by
	 * {@link Session#openChannel} to create channels.
	 */
	static Channel getChannel(String type) {
		if (type.equals("session")) {
			return new ChannelSession();
		}
		if (type.equals("shell")) {
			return new ChannelShell();
		}
		if (type.equals("exec")) {
			return new ChannelExec();
		}
		if (type.equals("x11")) {
			return new ChannelX11();
		}
		if (type.equals("auth-agent@openssh.com")) {
			return new ChannelAgentForwarding();
		}
		if (type.equals("direct-tcpip")) {
			return new ChannelDirectTCPIP();
		}
		if (type.equals("forwarded-tcpip")) {
			return new ChannelForwardedTCPIP();
		}
		if (type.equals("sftp")) {
			return new ChannelSftp();
		}
		if (type.equals("subsystem")) {
			return new ChannelSubsystem();
		}
		return null;
	}

	/**
	 * Retrieves a channel from the channel pool.
	 * 
	 * @param id
	 *            the session-specific identifier of the channel
	 * @param session
	 *            the session with which the channel is associated.
	 */
	static Channel getChannel(int id, Session session) {
		synchronized (pool) {
			for (int i = 0; i < pool.size(); i++) {
				Channel c = (Channel) (pool.elementAt(i));
				if (c.id == id && c.session == session)
					return c;
			}
		}
		return null;
	}

	/**
	 * Removes a channel from the channel pool.
	 */
	static void del(Channel c) {
		synchronized (pool) {
			pool.removeElement(c);
		}
	}

	int id;
	volatile int recipient = -1;
	protected byte[] type = Util.str2byte("foo");
	volatile int lwsize_max = 0x100000;
	volatile int lwsize = lwsize_max; // local initial window size
	volatile int lmpsize = 0x4000; // local maximum packet size

	volatile long rwsize = 0; // remote initial window size
	volatile int rmpsize = 0; // remote maximum packet size

	IO io = null;
	Thread thread = null;

	volatile boolean eof_local = false;
	volatile boolean eof_remote = false;

	volatile boolean close = false;
	volatile boolean connected = false;
	volatile boolean open_confirmation = false;

	volatile int exitstatus = -1;

	volatile int reply = 0;
	volatile int connectTimeout = 0;

	Session session;

	int notifyme = 0;

	Channel() {
		synchronized (pool) {
			id = index++;
			pool.addElement(this);
		}
	}

	synchronized void setRecipient(int foo) {
		this.recipient = foo;
		if (notifyme > 0)
			notifyAll();
	}

	int getRecipient() {
		return recipient;
	}

	void init() throws JSchException {
	}

	/**
	 * Opens the channel without any timeout. This is equivalent to
	 * {@link #connect(int) connect(0)} if not overridden in subclasses.
	 */
	public void connect() throws JSchException {
		connect(0);
	}

	/**
	 * Opens the channel. This sends a {@code SSH_MSH_CHANNEL_OPEN} message and
	 * waits until the response is received.
	 *
	 * <em>Warning:</em> Some subclasses override {@link #connect()} instead of
	 * this method, so calling this method with timeout parameter may then
	 * invoke the wrong method.
	 * 
	 * @param connectTimeout
	 *            the maximum time to wait for the channel to be established, in
	 *            milliseconds. If 0, we wait as long as needed (but at most
	 *            1000 times 50 milliseconds each).
	 * @throws JSchException
	 *             if a timeout occured, or some other connection problem.
	 */
	public void connect(int connectTimeout) throws JSchException {
		Session _session = getSession();
		if (!_session.isConnected()) {
			throw new JSchException("session is down");
		}
		this.connectTimeout = connectTimeout;
		try {
			Buffer buf = new Buffer(100);
			Packet packet = new Packet(buf);
			// send
			// byte SSH_MSG_CHANNEL_OPEN(90)
			// string channel type //
			// uint32 sender channel // 0
			// uint32 initial window size // 0x100000(65536)
			// uint32 maxmum packet size // 0x4000(16384)
			packet.reset();
			buf.putByte((byte) 90);
			buf.putString(this.type);
			buf.putInt(this.id);
			buf.putInt(this.lwsize);
			buf.putInt(this.lmpsize);
			_session.write(packet);
			int retry = 10;
			long start = System.currentTimeMillis();
			long timeout = connectTimeout;
			if (timeout != 0L)
				retry = 1;
			synchronized (this) {
				while (this.getRecipient() == -1 && _session.isConnected() && retry > 0) {
					if (timeout > 0L) {
						if ((System.currentTimeMillis() - start) > timeout) {
							retry = 0;
							continue;
						}
					}
					try {
						long t = timeout == 0L ? 5000L : timeout;
						this.notifyme = 1;
						wait(t);
					} catch (java.lang.InterruptedException e) {
					} finally {
						this.notifyme = 0;
					}
					retry--;
				}
			}
			if (!_session.isConnected()) {
				throw new JSchException("session is down");
			}
			if (this.getRecipient() == -1) { // timeout
				throw new JSchException("channel is not opened.");
			}
			if (this.open_confirmation == false) { // SSH_MSG_CHANNEL_OPEN_FAILURE
				throw new JSchException("channel is not opened.");
			}

			connected = true;
			start();
		} catch (Exception e) {
			connected = false;
			disconnect();
			if (e instanceof JSchException)
				throw (JSchException) e;
			throw new JSchException(e.toString(), e);
		}
	}

	/**
	 * Enables or disables X forwarding for this channel.
	 *
	 * This method does nothing here, but is implemented in subclasses for some
	 * types of channel ({@link ChannelShell}, {@link ChannelSftp},
	 * {@link ChannelExec}, {@link ChannelSubsystem}).
	 */
	public void setXForwarding(boolean foo) {
	}

	/**
	 * Not to be called externally. This method is called by
	 * {@link #connect(int)} when the connection is established.
	 *
	 * This implementation here does nothing, but it is overridden in some
	 * subclasses.
	 */
	public void start() throws JSchException {
	}

	/**
	 * Checks if we have already read all the data, i.e. whether the remote side
	 * sent an end-of-file notification for this channel.
	 */
	public boolean isEOF() {
		return eof_remote;
	}

	void getData(Buffer buf) {
		setRecipient(buf.getInt());
		setRemoteWindowSize(buf.getUInt());
		setRemotePacketSize(buf.getInt());
	}

	/**
	 * Sets the InputStream for this channel. The channel will then read from
	 * this stream and forward the data to the remote side. The stream will be
	 * closed on {@link #disconnect}. This method should be called before
	 * {@link #connect}.
	 */
	public void setInputStream(InputStream in) {
		io.setInputStream(in, false);
	}

	/**
	 * Sets the InputStream for this channel. The channel will then read from
	 * this stream and forward the data in SSH_MSG_CHANNEL_DATA to the remote
	 * side. This method should be called before {@link #connect}.
	 * 
	 * @param dontclose
	 *            if true, we do not close the stream after usage.
	 */
	public void setInputStream(InputStream in, boolean dontclose) {
		io.setInputStream(in, dontclose);
	}

	/**
	 * Sets the OutputStream for this channel. All data arriving in
	 * SSH_MSG_CHANNEL_DATA messages from the remote side will be written to
	 * this OutputStream. This method should be called before {@link #connect}.
	 * The stream will be closed on {@link #disconnect}.
	 * 
	 * @see #getInputStream
	 */
	public void setOutputStream(OutputStream out) {
		io.setOutputStream(out, false);
	}

	/**
	 * Sets the OutputStream for this channel. All data arriving in
	 * SSH_MSG_CHANNEL_DATA messages from the remote side will be written to
	 * this OutputStream. This method should be called before {@link #connect}.
	 * 
	 * @param dontclose
	 *            if true, we do not close the stream on {@link #disconnect}.
	 * @see #getInputStream
	 */
	public void setOutputStream(OutputStream out, boolean dontclose) {
		io.setOutputStream(out, dontclose);
	}

	/**
	 * Sets the OutputStream for extended data for this channel. All data
	 * arriving in SSH_MSG_CHANNEL_EXTENDED_DATA messages from the remote side
	 * will be written to this OutputStream.
	 * <p>
	 * <em>Note:</em> This implementation does not differentiate between
	 * different 'data_type_code' values, as <a
	 * href="http://tools.ietf.org/html/rfc4254#section-5.2">RFC 4254</a> only
	 * defines one type, namely SSH_EXTENDED_DATA_STDERR.
	 * </p>
	 * This method should be called before {@link #connect}.
	 *
	 * The stream will be closed on {@link #disconnect}.
	 * 
	 * @see #getExtInputStream
	 */
	public void setExtOutputStream(OutputStream out) {
		io.setExtOutputStream(out, false);
	}

	/**
	 * Sets the OutputStream for extended data for this channel. All data
	 * arriving in SSH_MSG_CHANNEL_EXTENDED_DATA messages from the remote side
	 * will be written to this OutputStream.
	 *
	 * <p>
	 * <em>Note:</em> This implementation does not differentiate between
	 * different 'data_type_code' values, as <a
	 * href="http://tools.ietf.org/html/rfc4254#section-5.2">RFC 4254</a> only
	 * defines one type, namely SSH_EXTENDED_DATA_STDERR.
	 * </p>
	 * This method should be called before {@link #connect}.
	 *
	 * @param dontclose
	 *            if true, we do not close the stream on {@link #disconnect}.
	 * @see #getExtInputStream
	 */
	public void setExtOutputStream(OutputStream out, boolean dontclose) {
		io.setExtOutputStream(out, dontclose);
	}

	/**
	 * Gets an InputStream for this channel. All data arriving in
	 * SSH_MSG_CHANNEL_DATA messages from the remote side can be read from this
	 * stream.
	 *
	 * This method is a polling alternative to {@link #setOutputStream}. It
	 * should be called before {@link #connect}.
	 */
	public InputStream getInputStream() throws IOException {
		// this valueshould becustomizable.
		PipedInputStream in = new MyPipedInputStream(32 * 1024);
		io.setOutputStream(new PassiveOutputStream(in), false);
		return in;
	}

	/**
	 * Gets an InputStream for extended data of this channel.
	 *
	 * All data arriving in SSH_MSG_CHANNEL_EXTENDED_DATA messages from the
	 * remote side can be read from this stream.
	 *
	 * This method is a polling alternative to {@link #setExtOutputStream}. It
	 * should be called before {@link #connect}.
	 */
	public InputStream getExtInputStream() throws IOException {
		// this value should be customizable.
		PipedInputStream in = new MyPipedInputStream(32 * 1024);
		io.setExtOutputStream(new PassiveOutputStream(in), false);
		return in;
	}

	/**
	 * Gets an OutputStream for this channel.
	 *
	 * All data written to this stream will be sent in SSH_MSG_CHANNEL_DATA
	 * messages to the remote side.
	 *
	 * This method is an alternative to {@link #setInputStream}. It should be
	 * called before {@link #connect}.
	 */
	public OutputStream getOutputStream() throws IOException {
		/*
		 * PipedOutputStream out=new PipedOutputStream(); io.setInputStream(new
		 * PassiveInputStream(out , 32*1024 ), false); return out;
		 */

		final Channel channel = this;
		OutputStream out = new OutputStream() {
			private int dataLen = 0;
			private Buffer buffer = null;
			private Packet packet = null;
			private boolean closed = false;

			private synchronized void init() throws java.io.IOException {
				buffer = new Buffer(rmpsize);
				packet = new Packet(buffer);

				byte[] _buf = buffer.buffer;
				if (_buf.length - (14 + 0) - Session.buffer_margin <= 0) {
					buffer = null;
					packet = null;
					throw new IOException("failed to initialize the channel.");
				}

			}

			byte[] b = new byte[1];

			public void write(int w) throws java.io.IOException {
				b[0] = (byte) w;
				write(b, 0, 1);
			}

			public void write(byte[] buf, int s, int l) throws java.io.IOException {
				if (packet == null) {
					init();
				}

				if (closed) {
					throw new java.io.IOException("Already closed");
				}

				byte[] _buf = buffer.buffer;
				int _bufl = _buf.length;
				while (l > 0) {
					int _l = l;
					if (l > _bufl - (14 + dataLen) - Session.buffer_margin) {
						_l = _bufl - (14 + dataLen) - Session.buffer_margin;
					}

					if (_l <= 0) {
						flush();
						continue;
					}

					System.arraycopy(buf, s, _buf, 14 + dataLen, _l);
					dataLen += _l;
					s += _l;
					l -= _l;
				}
			}

			public void flush() throws java.io.IOException {
				if (closed) {
					throw new java.io.IOException("Already closed");
				}
				if (dataLen == 0)
					return;
				packet.reset();
				buffer.putByte((byte) Session.SSH_MSG_CHANNEL_DATA);
				buffer.putInt(recipient);
				buffer.putInt(dataLen);
				buffer.skip(dataLen);
				try {
					int foo = dataLen;
					dataLen = 0;
					getSession().write(packet, channel, foo);
				} catch (Exception e) {
					close();
					throw new java.io.IOException(e.toString());
				}

			}

			public void close() throws java.io.IOException {
				if (packet == null) {
					try {
						init();
					} catch (java.io.IOException e) {
						// close should be finished silently.
						return;
					}
				}
				if (closed) {
					return;
				}
				if (dataLen > 0) {
					flush();
				}
				channel.eof();
				closed = true;
			}
		};
		return out;
	}

	class MyPipedInputStream extends PipedInputStream {
		MyPipedInputStream() throws IOException {
			super();
		}

		MyPipedInputStream(int size) throws IOException {
			super();
			buffer = new byte[size];
		}

		MyPipedInputStream(PipedOutputStream out) throws IOException {
			super(out);
		}

		MyPipedInputStream(PipedOutputStream out, int size) throws IOException {
			super(out);
			buffer = new byte[size];
		}

		/*
		 * We should have our own Piped[I/O]Stream implementation. Before
		 * accepting data, JDK's PipedInputStream will check the existence of
		 * reader thread, and if it is not alive, the stream will be closed.
		 * That behavior may cause the problem if multiple threads make access
		 * to it.
		 */
		public synchronized void updateReadSide() throws IOException {
			if (available() != 0) { // not empty
				return;
			}
			in = 0;
			out = 0;
			buffer[in++] = 0;
			read();
		}
	}

	void setLocalWindowSizeMax(int foo) {
		this.lwsize_max = foo;
	}

	void setLocalWindowSize(int foo) {
		this.lwsize = foo;
	}

	void setLocalPacketSize(int foo) {
		this.lmpsize = foo;
	}

	synchronized void setRemoteWindowSize(long foo) {
		this.rwsize = foo;
	}

	synchronized void addRemoteWindowSize(int foo) {
		this.rwsize += foo;
		if (notifyme > 0)
			notifyAll();
	}

	void setRemotePacketSize(int foo) {
		this.rmpsize = foo;
	}

	/**
	 * not to be called externally. This will be overridden by subclasses which
	 * need to do special processing of channel data.
	 */
	public void run() {
	}

	void write(byte[] foo) throws IOException {
		write(foo, 0, foo.length);
	}

	void write(byte[] foo, int s, int l) throws IOException {
		try {
			io.put(foo, s, l);
			String message = Util.getStringUTF8(foo, s, l);
			if (this.eventDelegate.isActive()) {
				this.eventDelegate.fire(message);
			} else {
				msgQueue.add(message);
			}
		} catch (NullPointerException e) {
		}
	}

	void write_ext(byte[] foo, int s, int l) throws IOException {
		try {
			io.put_ext(foo, s, l);
		} catch (NullPointerException e) {
		}
	}

	 public String getMessage() {
		 if (msgQueue.size() > 0) {
			 return (String) msgQueue.remove();
		 }
		 return null;
	 }

	/**
	 * Called by the session when the other end signals an end-of-file.
	 *
	 * We note this status and close the output stream to the application side.
	 */
	void eof_remote() {
		eof_remote = true;
		try {
			io.out_close();
		} catch (NullPointerException e) {
		}
	}

	void eof() {
		if (eof_local)
			return;
		eof_local = true;

		try {
			Buffer buf = new Buffer(100);
			Packet packet = new Packet(buf);
			packet.reset();
			buf.putByte((byte) Session.SSH_MSG_CHANNEL_EOF);
			buf.putInt(getRecipient());
			synchronized (this) {
				if (!close)
					getSession().write(packet);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// if (!isConnected()) {
		// disconnect();
		// }
	}

	/*
	 * http://tools.ietf.org/html/rfc4254#section-5.3
	 * 
	 * 5.3. Closing a Channel
	 * 
	 * When a party will no longer send more data to a channel, it SHOULD send
	 * SSH_MSG_CHANNEL_EOF.
	 * 
	 * byte SSH_MSG_CHANNEL_EOF uint32 recipient channel
	 * 
	 * No explicit response is sent to this message. However, the application
	 * may send EOF to whatever is at the other end of the channel. Note that
	 * the channel remains open after this message, and more data may still be
	 * sent in the other direction. This message does not consume window space
	 * and can be sent even if no window space is available.
	 * 
	 * When either party wishes to terminate the channel, it sends
	 * SSH_MSG_CHANNEL_CLOSE. Upon receiving this message, a party MUST send
	 * back an SSH_MSG_CHANNEL_CLOSE unless it has already sent this message for
	 * the channel. The channel is considered closed for a party when it has
	 * both sent and received SSH_MSG_CHANNEL_CLOSE, and the party may then
	 * reuse the channel number. A party MAY send SSH_MSG_CHANNEL_CLOSE without
	 * having sent or received SSH_MSG_CHANNEL_EOF.
	 * 
	 * byte SSH_MSG_CHANNEL_CLOSE uint32 recipient channel
	 * 
	 * This message does not consume window space and can be sent even if no
	 * window space is available.
	 * 
	 * It is RECOMMENDED that all data sent before this message be delivered to
	 * the actual destination, if possible.
	 */

	public void close() {
		if (close)
			return;
		close = true;
		eof_local = eof_remote = true;

		try {
			Buffer buf = new Buffer(100);
			Packet packet = new Packet(buf);
			packet.reset();
			buf.putByte((byte) Session.SSH_MSG_CHANNEL_CLOSE);
			buf.putInt(getRecipient());
			synchronized (this) {
				getSession().write(packet);
			}
		} catch (Exception e) {
			// e.printStackTrace();
		}
	}

	/**
	 * returns true if this channel is already closed (or another thread is in
	 * progress of closing the channel).
	 */
	public boolean isClosed() {
		return close;
	}

	/**
	 * disconnects all channels for one session.
	 */
	static void disconnect(Session session) {
		Channel[] channels = null;
		int count = 0;
		synchronized (pool) {
			channels = new Channel[pool.size()];
			for (int i = 0; i < pool.size(); i++) {
				try {
					Channel c = ((Channel) (pool.elementAt(i)));
					if (c.session == session) {
						channels[count++] = c;
					}
				} catch (Exception e) {
				}
			}
		}
		for (int i = 0; i < count; i++) {
			channels[i].disconnect();
		}
	}

	/**
	 * disconnects this channel.
	 */
	public void disconnect() {
		//Thread.dumpStack();
		try {

			synchronized (this) {
				if (!connected) {
					return;
				}
				connected = false;
			}

			close();

			eof_remote = eof_local = true;

			thread = null;

			try {
				if (io != null) {
					io.close();
				}
			} catch (Exception e) {
				// e.printStackTrace();
			}
			//io = null;
		} finally {
			del(this);
		}
	}

	/**
	 * returns true if this channel is currently connected (which also means
	 * that the session is still connected).
	 */
	public boolean isConnected() {
		Session _session = this.session;
		if (_session != null) {
			return _session.isConnected() && connected;
		}
		return false;
	}

	/**
	 * sends a signal to the process at the other side.
	 * 
	 * This is only useful for interactive channels.
	 * 
	 * @param signal
	 *            the signal name, without the "SIG" prefix.
	 * @see <a href="http://tools.ietf.org/html/rfc4254#section-6.9">RFC 4254,
	 *      Section 6.9. Signals</a>
	 */
	public void sendSignal(String signal) throws Exception {
		RequestSignal request = new RequestSignal();
		request.setSignal(signal);
		request.request(getSession(), this);
	}

//	 public String toString(){
//		 return "Channel: type="+new
//			 String(type)+",id="+id+",recipient="+recipient+",window_size="+window_size+",packet_size="+packet_size;
//	 }

//	class OutputThread extends Thread{ 
//		Channel c; 
//		OutputThread(Channel c){
//			this.c = c;
//		} 
//		public void run(){
//			c.output_thread();
//		} 
//	}

	class PassiveInputStream extends MyPipedInputStream {
		PipedOutputStream out;

		PassiveInputStream(PipedOutputStream out, int size) throws IOException {
			super(out, size);
			this.out = out;
		}

		PassiveInputStream(PipedOutputStream out) throws IOException {
			super(out);
			this.out = out;
		}

		public void close() throws IOException {
			if (out != null) {
				this.out.close();
			}
			out = null;
		}
	}

	class PassiveOutputStream extends PipedOutputStream {
		PassiveOutputStream(PipedInputStream in) throws IOException {
			super(in);
		}
	}

	void setExitStatus(int status) {
		exitstatus = status;
	}

	/**
	 * retrieves the exit status of the remote command corresponding to this
	 * channel.
	 *
	 * The exit status is only available for certain types of channels, and only
	 * after the channel was closed (more exactly, just before the channel is
	 * closed).
	 * 
	 * @return the exitstatus returned by the remote command, or -1, if the
	 *         command not yet terminated (or this channel type has no command).
	 * @see <a href="http://tools.ietf.org/html/rfc4254#section-6.10"> RFC 4254,
	 *      Section 6.10 Returning Exit Status</a>
	 */
	public int getExitStatus() {
		return exitstatus;
	}

	void setSession(Session session) {
		this.session = session;
	}

	/**
	 * Retrieves the session to which this channel belongs.
	 *
	 * This is mainly used internally.
	 * 
	 * @throws JSchException
	 *             if there is no such session.
	 */
	public Session getSession() throws JSchException {
		Session _session = session;
		if (_session == null) {
			throw new JSchException("session is not available");
		}
		return _session;
	}

	/**
	 * returns the session-specific identifier of the channel.
	 */
	public int getId() {
		return id;
	}

	/**
	 * sends a message confirming the opening of the channel.
	 */
	protected void sendOpenConfirmation() throws Exception {
		Buffer buf = new Buffer(100);
		Packet packet = new Packet(buf);
		packet.reset();
		buf.putByte((byte) SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
		buf.putInt(getRecipient());
		buf.putInt(id);
		buf.putInt(lwsize);
		buf.putInt(lmpsize);
		getSession().write(packet);
	}

	/**
	 * sends a message indicating the failure of a channel-opening to the remote
	 * side.
	 */
	protected void sendOpenFailure(int reasoncode) {
		try {
			Buffer buf = new Buffer(100);
			Packet packet = new Packet(buf);
			packet.reset();
			buf.putByte((byte) SSH_MSG_CHANNEL_OPEN_FAILURE);
			buf.putInt(getRecipient());
			buf.putInt(reasoncode);
			buf.putString(Util.str2byte("open failed"));
			buf.putString(Util.empty);
			getSession().write(packet);
		} catch (Exception e) {
		}
	}
	
	public void sendBytes(byte[] command) throws Exception {
		
	}
	
	public void send(String command) throws Exception {
		
	}
}
